import React, { Component } from 'react';
import { Button, Form, Input, Space, DatePicker, InputNumber, Radio, message, Descriptions } from "antd";
import TheQuill from "@/components/TheQuill";
import TheUpload from '@/components/TheUpload';
import TheButton from '@/components/TheButton';
import GoBack from "@/components/TheGoBack";
import TheTable from '@/components/TheTable';
import TheQueryForm from '@/components/TheQueryForm';
import ThePagination from '@/components/ThePagination';
import Json2Excel from '@/utils/Json2Excel'
import '../style.scss'
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import moment from "moment/moment";
import _ from 'lodash'
import { getDateTime3 } from '@/utils/getDate'
import { apiInviteActivityAdd, apiInviteActivityById, apiInviteActivityEdit, apiInviteActivityRecordPage, apiInviteActivityRecordExport } from '@/request/distribution/pullActivityList'

const { RangePicker } = DatePicker;

class Editor extends Component {
  constructor(props) {
    super(props)
    this.state = {
      type: "", // 页面进入的 类型
      fileList: [], //图片
      btnLoading: false, //确认按钮loading
      activityExplain: null, // 活动规则
      activityData: {}, // 活动数据概览
      inviteActivityId: '', //活动业务id
      columns: [
        {
          title: '用户名称',
          dataIndex: 'memberName',
          key: 'memberName',
        },
        {
          title: '用户ID',
          dataIndex: 'memberId',
          key: 'memberId',
        },
        {
          title: '注册时间',
          dataIndex: 'registeredTime',
          key: 'registeredTime',
        },
        {
          title: '是否激活',
          dataIndex: 'activateState',
          key: 'activateState',
          render: (text) => {
            let str = ''
            switch (text) {
              case '1':
                str = '已激活'
                break
              case '0':
                str = '未激活'
                break
            }
            return str
          }
        },
        {
          title: '分享活动次数',
          dataIndex: 'sharerCount',
          key: 'sharerCount',
        },

      ], //活动详情数据表头
      dataSource: [], //活动详情数据
      searchOption: [
        { field: 'memberId', label: '用户ID', placeholder: '输入用户ID', type: 'InputNumber', defaultValue: '' },
        {
          field: 'time', label: '时间', type: 'RangePicker'
        },
        {
          field: 'activateState',
          label: '活动状态',
          type: 'Select',
          placeholder: '选择活动状态',
          options: [{ value: '', label: '全部' },{ value: '0', label: '未激活' }, { value: '1', label: '已激活' }],
        },
      ],
      queryForm: {},
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      exportBtnLoading: false, //导出loading
    }
  }

  componentDidMount() {
    const { type, id } = this.props.match.params
    if (type === "add") {
      this.formRef.setFieldsValue({})
    } else {
      this.setState({ id }, () => {
        this.getData(id)
        this.getActivityData()
      })
    }
    this.setState({ type })
  }
  //数据处理
  getData = (id) => {
    apiInviteActivityById(id).then(res => {
      if (res.code === 0) {
        let inviteActivityDetailVoList = res.data.inviteActivityDetailVoList.map(item => {
          return {
            activatorsNumber: item.activatorsNumber,
            bonusAmount: item.bonusAmount,
            inviteActivityDetailId: item.inviteActivityDetailId ? item.inviteActivityDetailId : undefined
          }
        })
        let fields = {
          activityName: res.data.activityName, //活动名称
          time: [moment(res.data.startTime), moment(res.data.endTime)], //活动时间
          rewardPathway: res.data.rewardPathway, // 现金奖励类型
          rewardType: res.data.rewardType, // 活动奖励类型
          inviteActivityDetailVoList,  // 奖励人数金额 数组
          activityBanner: res.data.activityBanner, // 活动banner
          activityExplain: res.data.activityExplain, //活动规则
        }
        this.formRef.setFieldsValue({ ...fields })
        let fileList = [{
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: res.data.activityBanner,
        }]
        this.setState({
          fileList,
          activityExplain: res.data.activityExplain,
          activityData: {
            activateCount: res.data.activateCount ?? 0, //
            shareMemberCount: res.data.shareMemberCount ?? 0, // 
            shareMemberTimesCount: res.data.shareMemberTimesCount ?? 0, //
            memberCount: res.data.memberCount ?? 0, //邀请人数
          },
          inviteActivityId: res.data.inviteActivityId // 活动业务id
        })
      }
    })
  }
  // 活动数据详情 接口数据处理
  getActivityData = () => {
    let { pageData, queryForm, id } = this.state
    apiInviteActivityRecordPage({ inviteActivityIdStr: id, ...pageData, ...queryForm }).then(res => {
      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount
        })
      }
    })
  }
  //搜索
  onFormSearch(values) {
    //活动详情数据 搜索时间
    if (values && !_.isEmpty(values.time)) {
      values.startTime = getDateTime3(values.time[0]) + " 00:00:00"
      values.endTime = getDateTime3(values.time[1]) + " 23:59:59"
      delete values.time
    }
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: { ...values }
    }, () => {
      this.getActivityData()
    })
  }
  //搜索重置
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }

  // 活动数据详情分页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize },
      // source: false
    }, () => {
      this.getActivityData()
    })
  }
  /**
   * @desc 设置新闻内容表单默认值
   * */
  setNewsContent = (data) => {
    this.formRef.setFieldsValue({ activityExplain: data })
  }

  //图片上传回调
  getDetailsFileResult = value => {
    if (value.length && value[0] && value[0].response) {
      this.formRef.setFieldsValue({
        activityBanner: value[0].response.data
      })
    } else {
      this.formRef.setFieldsValue({
        activityBanner: ''
      })
    }
  }
  // 表单保存
  onFinish = async (value) => {
    value.rewardType = 'CASH_BONUS' //奖励类型 默认现金奖励 CASH_BONUS
    // 活动时间 数据处理
    if ('time' in value) {
      value.startTime = value.time[0].format('YYYY-MM-DD HH:mm:ss');
      value.endTime = value.time[1].format('YYYY-MM-DD HH:mm:ss');
      delete value.time;
    }
    // 现金奖励数据处理 选择上不封顶 默认人数为1 选择阶梯 按照填写数据进行处理
    if ('inviteActivityDetailVoList' in value) {
      value.inviteActivityDetailVoList = value.inviteActivityDetailVoList.map(item => {
        return {
          activatorsNumber: item.activatorsNumber || 1, //奖励人数
          bonusAmount: item.bonusAmount, // 奖励金额
          inviteActivityDetailId: item.inviteActivityDetailId ? item.inviteActivityDetailId : undefined // 编辑页面时 阶梯奖励修改的情况下要穿对应的id 
        }
      })
    }
    // 活动规则输入空的时候校验
    if (value.activityExplain === '<p></p>') {
      return React.$message({ type: 'error', content: '活动规则不能为空' })
    }
    this.setState({
      btnLoading: true
    })
    if (this.state.type === 'edit') {
      // 编辑时接口数据处理
      let res = await apiInviteActivityEdit({ ...value, inviteActivityId: this.state.inviteActivityId })
      if (res.code === 0) {
        this.setState({
          btnLoading: false
        }, async () => {
          this.props.history.goBack(-1)
          message.info('编辑成功')
        })
      } else {
        this.setState({ btnLoading: false })
      }
    } else {
      // 新建接口处理
      let res = await apiInviteActivityAdd(value)
      if (res.code === 0) {
        this.setState({
          btnLoading: false
        }, async () => {
          this.props.history.goBack(-1)
          message.info('提交成功')
        })
      } else {
        this.setState({ btnLoading: false })
      }
    }
    this.setState({ btnLoading: false })
  }
  // 活动奖励类型改变时 之前输入的现金奖励数据 做清空处理
  onValuesChange = (value, all) => {
    if ('rewardPathway' in value) {
      this.formRef.resetFields(['inviteActivityDetailVoList'])
    }
  }

  //导出
  getExport = () => {
    this.setState({ exportBtnLoading: true }, async () => {
      let tB_data = []
      let { inviteActivityId, queryForm } = this.state
      await apiInviteActivityRecordExport({ inviteActivityIdStr: inviteActivityId, ...queryForm }).then((res) => {
        if (res.code === 0) {
          tB_data = res.data.map(item => {
            console.log(item.sharerCount,'sharerCount');
            let activateState = ''
            switch (item.activateState) {
              case '1':
                activateState = '已激活'
                break
              case '0':
                activateState = '未激活'
                break
            }
            return {
              ...item,
              activateState,
            }
          })
          const option = {
            header: [
              { prop: 'memberName', title: '用户名称' },
              { prop: 'memberId', title: '用户ID' },
              { prop: 'registeredTime', title: '注册时间', width: 25 },
              { prop: 'activateState', title: '是否激活' },
              { prop: 'sharerCount', title: '分享活动次数', valueType: 'n'}
            ],
            dataSource: tB_data,
            fileName: '活动详情数据',
          }
          Json2Excel(option)
        }
      })
    })
    this.setState({ exportBtnLoading: false })
  }
  disabledDate = (current) => {
    // Can not select days before today and today
    return current && current < moment().startOf('day');
  };
  render() {
    const { fileList, type, activityData, btnLoading, activityExplain, columns, dataSource, searchOption, pageData: { pageNo, pageSize }, total, exportBtnLoading } = this.state
    let show = type === "add" ? true : false
    return <div className='p-layout-box'>
      <GoBack
        history={this.props.history}
        title={{ add: '新增', detail: '查看详情', edit: '修改' }[type]}
      />
      <div className="p-layout-content" style={{ margin: '10px 60px ', overflowY: 'initial' }}>
        <div className='activityItem label'>
          <div className='bookmark'>活动信息</div>
          <div className='triangle'></div>
        </div>
        <Form
          ref={ref => {
            this.formRef = ref
          }}
          labelCol={{ flex: '100px' }}
          wrapperCol={{ span: 16 }}
          onFinish={this.onFinish}
          onValuesChange={this.onValuesChange}
        >
          <Form.Item
            name={'activityName'}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")} //不能输入空格
            rules={[{ required: true, message: '活动名称为必填项' }]}
            label={'活动名称'}
          >
            <Input disabled={type == 'detail'} maxLength={15} style={{ width: '400px' }} placeholder='请输入名称' />
          </Form.Item>
          <Form.Item
            name={'time'}
            rules={[{ required: true, message: '活动时间为必填项' }]}
            label={'活动时间'}
          >
            <RangePicker disabled={type == 'detail'} showTime={{defaultValue: moment('00:00:00', 'HH:mm:ss'),}} style={{ width: '400px' }} disabledDate={this.disabledDate} />
          </Form.Item>
          <Form.Item label={'活动奖励'} required style={{ marginBottom: 0 }}>
            <span>现金奖励</span>
          </Form.Item>
          <Form.Item label={' '} name={'rewardPathway'} colon={false} rules={[
            {
              validator: async (_, rewardPathway) => {
                if (rewardPathway === undefined) { return Promise.reject(new Error('活动奖励为必填项')) }
              }
            }
          ]}>
            <Radio.Group disabled={type == 'detail'}>
              <Space direction="vertical">
                <Radio value={'NO_CAP_ON_CASH_REWARDS'}>
                  上不封顶现金奖励
                  <Form.Item noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.rewardPathway !== currentValues.rewardPathway}>
                    {({ getFieldValue }) =>
                      getFieldValue('rewardPathway') === 'NO_CAP_ON_CASH_REWARDS' ? (
                        <Form.List name="inviteActivityDetailVoList" initialValue={[
                          {
                            activatorsNumber: null,
                            bonusAmount: null
                          }
                        ]}
                        >
                          {(fields, { add, remove }, { errors }) => (
                            <>
                              {fields.map(({ key, name, ...restField }) => (
                                <Space key={key} align="baseline" style={{ display: 'flex' }}>
                                  <div>每激活1人，奖励爱宠分享官</div>
                                  <Form.Item
                                    name={[name, 'bonusAmount']}
                                    getValueProps={v => ({
                                      value: v ? React.$transNum(v, 2, -2) : null,
                                      v
                                    })}
                                    getValueFromEvent={e => e ? e * 100 : e}
                                    rules={[{ required: true, message: '此项为必填项' }]}
                                    style={{ marginBottom: 0 }}
                                  >
                                    <InputNumber
                                      placeholder='请输入金额'
                                      style={{ width: '100px' }}
                                      min={1}
                                      max={999}
                                      precision={0}
                                      disabled={type == 'detail'}
                                    />
                                  </Form.Item>
                                  <span>元</span>
                                </Space>
                              ))}
                            </>
                          )}
                        </Form.List>
                      ) : null}
                  </Form.Item>
                </Radio>
                <Radio value={'LADDER_CASH_REWARDS'}>
                  阶梯现金奖励
                  <Form.Item noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.rewardPathway !== currentValues.rewardPathway}>
                    {({ getFieldValue }) =>
                      getFieldValue('rewardPathway') === 'LADDER_CASH_REWARDS' ? (
                        <Form.List name="inviteActivityDetailVoList" initialValue={[
                          {
                            activatorsNumber: null,
                            bonusAmount: null
                          }
                        ]}
                        >
                          {(fields, { add, remove }, { errors }) => (
                            <>
                              {fields.map(({ key, name, ...restField }) => (
                                <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                  <div>激活</div>
                                  <Form.Item
                                    {...restField}
                                    name={[name, 'activatorsNumber']}
                                    rules={[{ required: true, message: '此项为必填项' }]}
                                  >
                                    <InputNumber
                                      placeholder='请输入人数'
                                      style={{ width: '100px' }}
                                      min={1}
                                      max={999}
                                      precision={0}
                                      disabled={type == 'detail'}
                                    />
                                  </Form.Item>
                                  <span>人</span>
                                  <span>奖励</span>
                                  <Form.Item
                                    {...restField}
                                    name={[name, 'bonusAmount']}
                                    rules={[{ required: true, message: '此项为必填项' }]}
                                    getValueProps={v => ({
                                      value: v ? React.$transNum(v, 2, -2) : null,
                                      v
                                    })}
                                    getValueFromEvent={e => e ? e * 100 : e}
                                  >
                                    <InputNumber
                                      placeholder='请输入金额'
                                      style={{ width: '100px' }}
                                      precision={0}
                                      min={1}
                                      max={999}
                                      // formatter={this.formatter}
                                      disabled={type == 'detail'}

                                    />
                                  </Form.Item>
                                  <span>元</span>
                                  {type !== 'detail' ? key === 0 ? null : <CloseOutlined className="close" onClick={() => remove(name)} /> : null}
                                </Space>
                              ))}
                              {
                                type !== 'detail' && <Form.Item style={{ marginBottom: 0 }}>
                                  <Button style={{ width: '400px' }} type="dashed" onClick={() => {
                                    if (fields.length >= 10) {
                                      message.warning('不能再新增了哦~')
                                    } else {
                                      add()
                                    }
                                  }} icon={<PlusOutlined />}>
                                    增加奖励
                                  </Button>
                                  <Form.ErrorList errors={errors} />
                                </Form.Item>
                              }
                            </>
                          )}
                        </Form.List>
                      ) : null}
                  </Form.Item>
                </Radio>
              </Space>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label={'活动banner'}
            name={'activityBanner'}
            rules={[{ required: true, message: '请上传活动banner' }]}
            extra={'支持jpg .jpeg .bmp .png格式,大小不超过5M,最多上传1张,建议尺寸: 1404pt*392pt'}
          >
            {fileList &&
              <TheUpload
                accept={['image/jpg', 'image/jpeg', 'image/bmp', 'image/png']}
                fileList={fileList}
                maxSize={5}
                len={1}
                isShowRemoveIcon={type !== 'detail'}
                getFileResult={this.getDetailsFileResult}
              />
            }
          </Form.Item>
          <Form.Item
            name={'activityExplain'}
            rules={[{ required: true, message: '请填写活动规则' }]}
            label={'活动规则'}
          >
            {type === 'detail' && <div style={{ padding: 5 }} dangerouslySetInnerHTML={{ __html: activityExplain }} />}
            {type === 'add' && <TheQuill defaultValue={null} disUploadImg={true} setNewsContent={this.setNewsContent} />}
            {(type === 'edit' && activityExplain) && <TheQuill defaultValue={!show ? activityExplain : null} disUploadImg={true} setNewsContent={this.setNewsContent} />}
          </Form.Item>
          {
            type !== 'detail' && <div className="p-text-align">
              <Space size="large">
                <Button key="back" onClick={() => this.props.history.goBack(-1)}>
                  取 消
                </Button>
                <Button type="primary" loading={btnLoading} htmlType="primary">
                  确 定
                </Button>
              </Space>
            </div>
          }

        </Form>
        {
          type === 'detail' && <>
            <div className='activityItem label'>
              <div className='bookmark'>活动效果</div>
              <div className='triangle'></div>
            </div>
            <Descriptions
              title="活动数据概览"
              column={4}
              layout="vertical"
              bordered
              labelStyle={{ display: 'block', textAlign: 'center' }}
              contentStyle={{ display: 'block', textAlign: 'center' }}
            >
              <Descriptions.Item label="分享人数（去重）">{activityData.shareMemberCount}</Descriptions.Item>
              <Descriptions.Item label="分享次数">{activityData.shareMemberTimesCount}</Descriptions.Item>
              <Descriptions.Item label="注册人数">{activityData.memberCount}</Descriptions.Item>
              <Descriptions.Item label="激活人数">{activityData.activateCount}</Descriptions.Item>
            </Descriptions>
            <br />
            <Descriptions title="活动详情数据" ></Descriptions>
            <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption}
              onGetValues={(values) => this.onFormSearch(values)}
              onReset={(values) => this.onReset(values)}
            >
              <TheButton loading={exportBtnLoading} type='default' size='middle' onClick={() => this.getExport()}>导出</TheButton>
            </TheQueryForm>
            <TheTable dataSource={dataSource} columns={columns} />
            <ThePagination
              pageNo={pageNo}
              pageSize={pageSize}
              total={total}
              pageChange={this.pageChange}
            />
          </>
        }
      </div>
    </div>
  }
}
export default Editor;
